package com.shiyi.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.shiyi.core.vo.Role;
import com.shiyi.system.entity.SysRole;
import com.shiyi.system.mapper.SysRoleMapper;
import com.shiyi.system.service.SysMenuRoleService;
import com.shiyi.system.service.SysRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.ibatis.executor.loader.cglib.CglibProxyFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author shiyi
 * @since 2020-11-19
 */
@Service
@Transactional
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {


    @Autowired
    private SysMenuRoleService sysMenuRoleService;

    @Override
    public List<Role> queryRolesByUserId(Integer userId) {
        return this.baseMapper.queryRolesByUserId(userId);
    }

    @Override
    public List<SysRole> listRole(String keyword) {
        return this.baseMapper.listRole(keyword);
    }

    @Override
    public boolean getRoleByCode(String roleCode) {
        QueryWrapper<SysRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role_code", roleCode);
        return this.getOne(queryWrapper) == null;
    }

    @Override
    public boolean insertRole(SysRole role) {
        role.setCreateTime(new Date());
        role.setUpdateTime(new Date());
        // 新增角色成功后，新增角色菜单信息
        if (this.save(role)) {
            return sysMenuRoleService.saveMenuRole(role.getId(), role.getMenuIds());
        }
        return false;
    }

    @Override
    public boolean getRoleByCodeAndId(Integer id, String roleCode) {
        QueryWrapper<SysRole> wrapper = new QueryWrapper<>();
        wrapper.ne("id", id);
        wrapper.eq("role_code", roleCode);
        return this.getOne(wrapper) == null;
    }

    @Override
    public boolean updateRole(SysRole role) {
        role.setUpdateTime(new Date());
        if (this.updateById(role)) {
            if (sysMenuRoleService.deleteByRoleId(role.getId())) {
                return sysMenuRoleService.saveMenuRole(role.getId(), role.getMenuIds());
            }
        }
        return false;
    }

    @Override
    public boolean deleteRole(Integer id) {
        UpdateWrapper<SysRole> wrapper = new UpdateWrapper<>();
        wrapper.eq("id", id);
        wrapper.set("is_delete", 2);
        wrapper.set("update_time", new Date());
        return this.update(wrapper);
    }
}
